import requests
from bs4 import BeautifulSoup

# 获取天气信息
def crawer_weather(city_name):
    try:
        res = requests.get(f'http://www.weather.com.cn/weather/{city_code_map.get(city_name)}.shtml')
        res.encoding = 'utf-8'
        soup1 = BeautifulSoup(res.text, 'html.parser')
        # tianqi = soup1.find('input', id='hidden_title')['value']
        # split = tianqi.split(" ")
        # return {
        #     "city": city_name,
        #     "description": split[3],
        #     "current_temp": split[3] + ' ' + split[5].replace("°C","")
        # }
        # 查找所有天气预报条目

        weather_list = []
        days = soup1.find_all('li', class_='sky')

        for day in days:
            date = day.find('h1').text.strip()
            weather_condition = day.find('p', class_='wea').text.strip()

            temp = day.find('p', class_='tem')
            high_temp = temp.find('span').text.strip()
            low_temp = temp.find('i').text.strip()

            wind = day.find('p', class_='win')
            wind_directions = [span['title'] for span in wind.em.find_all('span', title=True)]
            wind_strength = wind.find('i').text.strip()
            weather_list.append({
                'date': date,
                'weather': weather_condition,
                'temperature': low_temp+' ~ '+high_temp,
                'wind_directions': wind_directions[0]+'：'+wind_strength
            })

        return weather_list
    except Exception as e:
        pass

# 城市编码映射
city_code_map = {
    "北京": "101010100",
    "西安": "101110101",
    "太原": "101100101",
    "大同": "101100201",
    "阳泉": "101100301",
    "榆次": "101100402",
    "长治": "101100501",
    "运城": "101100801",
}

# 中英文城市名称映射
city_translation = {
    "北京": "Beijing",
    "西安": "Xi'an",
    "太原": "Taiyuan",
    "大同": "Datong",
    "阳泉": "Yangquan",
    "榆次": "Yuci",
    "长治": "Changzhi",
    "运城": "Yuncheng",
}

# 英文天气描述到中文的映射
weather_translation = {
    "clear sky": "晴天",
    "few clouds": "少量云",
    "scattered clouds": "间歇性云",
    "broken clouds": "多云",
    "shower rain": "阵雨",
    "rain": "雨",
    "thunderstorm": "雷暴",
    "snow": "雪",
    "mist": "雾霾",
    "overcast clouds": "阴天",
}
# 入口
def get_weather(city_name):
    return crawer_weather(city_name)

def get_weather_seniverse(city_name):
    api_key = 'Ss0Kb_vyaqvjmZ0uf'
    url = f'https://api.seniverse.com/v3/weather/now.json'

    params = {
        'key': api_key,  # 替换为你的API密钥
        'location': city_name,  # 城市名称（如北京，上海）
        'language': 'zh-Hans',
        'unit': 'c'  # 温度单位为摄氏度
    }
    try:
        # 发送GET请求
        response = requests.get(url, params=params)
        data = response.json()  # 将响应内容解析为JSON
        # 检查API返回的状态码
        if response.status_code == 200:
            if 'results' in data and len(data['results']) > 0:
                weather = data['results'][0]['now']['text']
                temperature = data['results'][0]['now']['temperature']

                return {
                    "city": city_name,
                    "description": weather,
                    "current_temp": temperature
                }
            else:
                print("无法获取天气数据，请检查城市名称或API密钥")
        else:
            print(f"请求失败，HTTP状态码: {response.status_code}")
    except requests.exceptions.RequestException as e:
        print(f"请求发生错误: {e}")
    except KeyError as e:
        print(f"解析返回数据时发生错误，缺少字段: {e}")
    except Exception as e:
        print(f"发生未知错误: {e}")
    return None

def get_weather_openWeather(city):
    city_english = city_translation.get(city, city)  # 如果找不到对应的英文名，使用原城市名

    api_key = '010032e3f87180b0424cb1fe63af1aa0'
    base_url = f'https://api.openweathermap.org/data/2.5/weather?q={city_english}&units=metric&APPID={api_key}'  # 使用英文城市名查询
    response = requests.get(base_url)

    if response.status_code == 200:
        data = response.json()
        main = data['main']
        weather_desc = data['weather'][0]['description']
        temperature = main['temp']
        temp_max = main['temp_max']  # 最高气温
        temp_min = main['temp_min']  # 最低气温

        # 翻译天气描述为中文
        weather_desc_cn = weather_translation.get(weather_desc, weather_desc)

        # 返回获取的天气信息
        return {
            "city": city,
            "description": weather_desc_cn,
            "current_temp": temperature,
            "temp_max": temp_max,
            "temp_min": temp_min
        }
    else:
        return None


def get_all_cities_weather():
    result_map = city_code_map.copy()
    try:
        for city in city_translation.keys():
            result_map[city] = get_weather(city)
    except Exception as e:
        print('error', e)
    return result_map


if __name__ == "__main__":
    print(get_all_cities_weather())
